<template>
	<view class="container">
		<!-- 头部信息 -->
		<view class="header">
			<view class="title">试卷详情</view>
			<view class="actions">
				<button class="action-btn" :class="{'btn-active': examInfo.status === 'active', 'btn-paused': examInfo.status === 'paused'}" @click="toggleExamStatus">
					{{examInfo.status === 'active' ? '暂停考试' : '激活考试'}}
				</button>
				<button class="action-btn btn-share" open-type="share">分享</button>
			</view>
		</view>
		
		<!-- 基本信息 -->
		<view class="info-card">
			<view class="card-title">{{examInfo.title || '未命名试卷'}}</view>
			<view class="info-content">
				<view class="info-item">
					<text class="label">创建时间：</text>
					<text class="value">{{formatDate(examInfo.create_date || examInfo.createTime)}}</text>
				</view>
				<view class="info-item">
					<text class="label">试卷类型：</text>
					<text class="value">{{examInfo.exam_type || examInfo.examType || '未知类型'}}</text>
				</view>
				<view class="info-item">
					<text class="label">状态：</text>
					<text class="value" :class="{'active-text': examInfo.status === 'active', 'paused-text': examInfo.status === 'paused'}">
						{{examInfo.status === 'active' ? '已激活' : '已暂停'}}
					</text>
				</view>
				<view class="info-item">
					<text class="label">通过分数：</text>
					<text class="value">{{examInfo.pass_score || examInfo.passScore || 60}}分</text>
				</view>
				<view class="info-item">
					<text class="label">考试时长：</text>
					<text class="value">{{examInfo.time_limit || examInfo.timeLimit || 60}}分钟</text>
				</view>
				<view class="info-item">
					<text class="label">题目数量：</text>
					<text class="value">{{(examInfo.questions && examInfo.questions.length) || 0}}题</text>
				</view>
			</view>
		</view>
		
		<!-- 统计信息 -->
		<view class="stats-card">
			<view class="card-title">考试数据统计</view>
			<view class="stats-content">
				<view class="stats-row">
					<view class="stats-item">
						<view class="stats-value">{{analytics.participantCount || 0}}</view>
						<view class="stats-label">参与人数</view>
					</view>
					<view class="stats-item">
						<view class="stats-value">{{analytics.avgScore || 0}}</view>
						<view class="stats-label">平均分</view>
					</view>
					<view class="stats-item">
						<view class="stats-value">{{analytics.passRate || 0}}%</view>
						<view class="stats-label">通过率</view>
					</view>
				</view>
				<view class="stats-row">
					<view class="stats-item">
						<view class="stats-value">{{analytics.highestScore || 0}}</view>
						<view class="stats-label">最高分</view>
					</view>
					<view class="stats-item">
						<view class="stats-value">{{analytics.lowestScore || 0}}</view>
						<view class="stats-label">最低分</view>
					</view>
					<view class="stats-item">
						<view class="stats-value">{{analytics.shareCount || 0}}</view>
						<view class="stats-label">分享次数</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分数分布图表 -->
		<view class="chart-card" v-if="hasParticipants">
			<view class="card-title">分数分布</view>
			<view class="chart-container">
				<view class="score-distribution">
					<view class="dist-item" v-for="(item, index) in analytics.scoreDistribution" :key="index">
						<view class="dist-bar" :style="{height: getBarHeight(item.count)}">
							<text class="dist-count">{{item.count}}</text>
						</view>
						<view class="dist-label">{{item.range}}</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 题目错误分布 -->
		<view class="chart-card" v-if="hasParticipants">
			<view class="card-title">题目答错率</view>
			<view class="chart-container">
				<view class="question-error-rate">
					<view class="error-item" v-for="(item, index) in analytics.questionStats" :key="index">
						<view class="error-info">
							<text class="question-number">第{{index + 1}}题</text>
							<text class="error-rate">错误率: {{item.errorRate}}%</text>
						</view>
						<view class="error-bar-container">
							<view class="error-bar" :style="{width: item.errorRate + '%'}"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分享弹窗 -->
		<view class="share-popup" v-if="showSharePopup">
			<view class="share-content">
				<view class="share-title">分享试卷</view>
				<view class="share-info">
					<text>试卷：{{examInfo.title}}</text>
					<text>分享码：{{shareInfo.shareCode}}</text>
				</view>
				<view class="share-actions">
					<button class="share-btn" @click="copyShareInfo">复制链接</button>
					<button class="share-btn share-cancel" @click="closeSharePopup">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				examId: '',
				userToken: '',
				examInfo: {},
				analytics: {
					participantCount: 0,
					avgScore: 0,
					passRate: 0,
					highestScore: 0,
					lowestScore: 0,
					shareCount: 0,
					scoreDistribution: [],
					questionStats: []
				},
				showSharePopup: false,
				shareInfo: {
					shareCode: '',
					shareParams: ''
				},
				loading: false
			}
		},
		computed: {
			hasParticipants() {
				return this.analytics.participantCount > 0;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.examId = options.id;
				// 获取用户信息和Token
				this.getUserInfo().then(() => {
					// 获取试卷详情
					this.getExamDetail();
					// 获取统计数据
					this.getExamAnalytics();
				});
			} else {
				uni.showToast({
					title: '缺少试卷ID',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		// 分享到聊天
		onShareAppMessage() {
			return {
				title: this.examInfo.title || '考试试卷',
				path: `/packageExam/exam/exam-details?id=${this.examId}`,
				imageUrl: this.examInfo.coverImage || '/static/images/default-cover.png',
				success: () => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					});
				}
			};
		},
		// 分享到朋友圈
		onShareTimeline() {
			return {
				title: this.examInfo.title || '考试试卷',
				query: `id=${this.examId}`,
				imageUrl: this.examInfo.coverImage || '/static/images/default-cover.png'
			};
		},
		methods: {
			// 获取用户信息和Token
			getUserInfo() {
				return new Promise((resolve, reject) => {
					try {
						const userInfo = uni.getStorageSync('userInfo');
						if (userInfo) {
							this.userInfo = JSON.parse(userInfo);
							this.userToken = uni.getStorageSync('token') || '';
							console.log('当前用户token:', this.userToken);
							
							// 验证token有效性
							(async () => {
								try {
									const userService = uniCloud.importObject('user-service');
									const res = await userService.verifyToken({
									token: this.userToken
									});
									
									console.log('验证token结果:', res);
									if (res.code !== 0) {
										// token无效，尝试刷新
										const newToken = await this.refreshToken();
											if (newToken) {
												this.userToken = newToken;
												resolve(this.userInfo);
											} else {
												// 刷新失败，跳转登录
												this.redirectToLogin('登录已过期，请重新登录');
												reject('登录已过期');
											}
									} else {
										resolve(this.userInfo);
									}
								} catch (err) {
									console.error('验证token失败', err);
									reject(err);
								}
							})();
						} else {
							uni.showToast({
								title: '请先登录',
								icon: 'none'
							});
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/login/login'
								});
							}, 1500);
							reject('用户未登录');
						}
					} catch (e) {
						console.error('获取用户信息失败', e);
						reject(e);
					}
				});
			},
			
			// 刷新token
			async refreshToken() {
				try {
					const userService = uniCloud.importObject('user-service');
					const res = await userService.refreshToken({
							token: this.userToken
					});
					
					console.log('刷新token结果:', res);
					if (res.code === 0 && res.data && res.data.token) {
								// 更新本地token
						const newToken = res.data.token;
								uni.setStorageSync('token', newToken);
								console.log('token已刷新并更新');
						return newToken;
							} else {
						console.error('刷新token失败:', res.message);
						return null; // 刷新失败返回null
							}
				} catch (err) {
							console.error('刷新token请求失败', err);
					return null;
						}
			},
			
			// 重定向到登录页
			redirectToLogin(message) {
				uni.showToast({
					title: message || '请先登录',
					icon: 'none'
				});
				
				// 清除本地存储的token和用户信息
				uni.removeStorageSync('token');
				
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
			},
			
			// 获取试卷详情
			async getExamDetail() {
				uni.showLoading({
					title: '加载中...'
				});
				
				console.log('用户信息:', this.userInfo);
				console.log('试卷信息:', this.examInfo);
				console.log('请求的examId:', this.examId);
				
				try {
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.getExamDetail({
						examId: this.examId,
						token: this.userToken
					});
					
						uni.hideLoading();
					if (res.code === 0) {
						this.examInfo = res.data;
							console.log('试卷详情:', this.examInfo);
						} else {
							uni.showToast({
							title: res.message || '获取试卷详情失败',
								icon: 'none'
							});
						}
				} catch (err) {
						uni.hideLoading();
						console.error('获取试卷详情失败', err);
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
			},
			
			// 获取考试记录数据
			async getExamRecords() {
				uni.showLoading({
					title: '加载考试记录...'
				});
				
				try {
					// 调用admin-service云对象获取考试记录
					const adminService = uniCloud.importObject('admin-service');
					const res = await adminService.getAdminExamRecords({
						examId: this.examId,
						token: this.userToken,
						page: 1,
						limit: 20
					});
					
						uni.hideLoading();
					console.log('获取考试记录返回:', res);
						
					if (res.code === 0) {
							// 使用获取到的考试记录更新统计信息
						const recordsData = res.data || {};
							const statistics = recordsData.statistics || {};
							
							// 更新统计数据
							this.analytics.participantCount = statistics.totalCount || 0;
							this.analytics.avgScore = statistics.avgScore || 0;
							this.analytics.passRate = parseInt(statistics.passRate) || 0;
							
							console.log('更新后的统计数据:', this.analytics);
						} else {
						console.error('获取考试记录失败:', res.message);
						}
				} catch (err) {
						uni.hideLoading();
						console.error('获取考试记录失败:', err);
					}
			},
			
			// 获取试卷统计分析数据
			async getExamAnalytics() {
				uni.showLoading({
					title: '加载分析数据...'
				});
				
				try {
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.getExamAnalytics({
						examId: this.examId,
						token: this.userToken
					});
					
						uni.hideLoading();
					if (res.code === 0) {
							// 使用getExamAnalytics的返回数据
						const analyticsData = res.data;
							this.analytics = {
								participantCount: analyticsData.participantCount || 0,
								avgScore: analyticsData.avgScore || 0,
								passRate: analyticsData.passRate || 0,
								highestScore: analyticsData.highestScore || 0,
								lowestScore: analyticsData.lowestScore || 0,
								shareCount: analyticsData.shareCount || 0,
								// 转换分数分布数据格式
								scoreDistribution: [
									{ range: '0-59', count: analyticsData.scoreDistribution?.['0-59'] || 0 },
									{ range: '60-69', count: analyticsData.scoreDistribution?.['60-69'] || 0 },
									{ range: '70-79', count: analyticsData.scoreDistribution?.['70-79'] || 0 },
									{ range: '80-89', count: analyticsData.scoreDistribution?.['80-89'] || 0 },
									{ range: '90-100', count: analyticsData.scoreDistribution?.['90-100'] || 0 }
								],
								// 转换题目统计数据
								questionStats: analyticsData.questionStats || []
							};
							
							// 为每个题目计算错误率
							if (this.analytics.questionStats.length > 0) {
								this.analytics.questionStats = this.analytics.questionStats.map(item => {
									const totalAttempts = item.correctCount + item.wrongCount;
									const errorRate = totalAttempts > 0 ? 
										Math.round((item.wrongCount / totalAttempts) * 100) : 0;
									
									return {
										...item,
										errorRate
									};
								});
							}
							
							console.log('统计数据:', this.analytics);
							
							// 如果getExamAnalytics没有返回参与人数，调用getExamRecords获取
							if (!analyticsData.participantCount) {
								this.getExamRecords();
							}
						} else {
						console.error('获取统计数据失败:', res);
							
							// 如果获取统计数据失败，尝试从考试记录获取
							this.getExamRecords();
						}
				} catch (err) {
						uni.hideLoading();
						console.error('获取统计数据失败', err);
						
						// 如果获取统计数据失败，尝试从考试记录获取
						this.getExamRecords();
					}
			},
			
			// 切换试卷状态（激活/暂停）
			async toggleExamStatus() {
				if (this.loading) return;
				this.loading = true;
				
				const newStatus = this.examInfo.status === 'active' ? 'paused' : 'active';
				
				uni.showLoading({
					title: newStatus === 'active' ? '正在激活...' : '正在暂停...'
				});
				
				try {
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.updateExamStatus({
						examId: this.examId,
						status: newStatus,
						token: this.userToken
					});
					
						this.loading = false;
						uni.hideLoading();
						
					if (res.code === 0) {
							// 更新状态成功
							this.examInfo.status = newStatus;
							uni.showToast({
								title: newStatus === 'active' ? '已激活' : '已暂停',
								icon: 'success'
							});
						} else {
							uni.showToast({
							title: res.message || '操作失败',
								icon: 'none'
							});
						}
				} catch (err) {
						this.loading = false;
						uni.hideLoading();
						console.error('更新试卷状态失败', err);
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
			},
			
			// 分享试卷
			shareExam() {
				if (this.loading) return;
				
				// 在微信小程序中使用分享菜单
				if (uni.getSystemInfoSync().platform === 'mp-weixin') {
					uni.showShareMenu({
						withShareTicket: true,
						menus: ['shareAppMessage', 'shareTimeline']
					});
				} else {
					// 非微信小程序环境使用原来的分享弹窗
					this.loading = true;
					
					uni.showLoading({
						title: '生成分享信息...'
					});
					
					(async () => {
						try {
							const examService = uniCloud.importObject('exam-service');
							const res = await examService.shareExam({
							examId: this.examId,
							token: this.userToken,
							shareType: 'wechat'
							});
							
							this.loading = false;
							uni.hideLoading();
							
							if (res.code === 0) {
								// 显示分享信息
								this.shareInfo = {
									shareCode: res.data.shareCode,
									shareParams: res.data.shareParams,
									examTitle: res.data.examTitle
								};
								this.showSharePopup = true;
							} else {
								uni.showToast({
									title: res.message || '分享失败',
									icon: 'none'
								});
							}
						} catch (err) {
							this.loading = false;
							uni.hideLoading();
							console.error('分享试卷失败', err);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					})();
				}
			},
			
			// 复制分享信息
			copyShareInfo() {
				const shareLink = `试卷: ${this.examInfo.title}\n分享码: ${this.shareInfo.shareCode}`;
				
				uni.setClipboardData({
					data: shareLink,
					success: () => {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'success'
						});
						this.closeSharePopup();
					}
				});
			},
			
			// 关闭分享弹窗
			closeSharePopup() {
				this.showSharePopup = false;
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '未知时间';
				
				let date;
				if (typeof timestamp === 'object') {
					date = timestamp;
				} else {
					date = new Date(timestamp);
				}
				
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			},
			
			// 获取图表柱高
			getBarHeight(count) {
				if (!count) return '0%';
				
				// 找出最大值
				const maxCount = Math.max(...this.analytics.scoreDistribution.map(item => item.count));
				
				if (maxCount === 0) return '0%';
				
				// 计算高度比例（最大高度80%）
				const percent = Math.round((count / maxCount) * 80);
				return `${percent}%`;
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 30rpx;
	}
	
	.header {
		background-color: #007AFF;
		color: #ffffff;
		padding: 40rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.actions {
		display: flex;
	}
	
	.action-btn {
		font-size: 24rpx;
		margin-left: 20rpx;
		background-color: #ffffff;
		color: #007AFF;
		border-radius: 30rpx;
		padding: 10rpx 20rpx;
		border: none;
		line-height: 1.5;
	}
	
	.btn-active {
		background-color: #FF3B30;
		color: #ffffff;
	}
	
	.btn-paused {
		background-color: #34C759;
		color: #ffffff;
	}
	
	.btn-share {
		background-color: #FF9500;
		color: #ffffff;
	}
	
	.info-card, .stats-card, .chart-card {
		background-color: #ffffff;
		border-radius: 12rpx;
		margin: 20rpx 30rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		border-bottom: 1px solid #eeeeee;
		padding-bottom: 15rpx;
	}
	
	.info-content, .stats-content {
		padding: 10rpx 0;
	}
	
	.info-item {
		display: flex;
		margin-bottom: 20rpx;
	}
	
	.label {
		color: #666666;
		width: 180rpx;
		flex-shrink: 0;
	}
	
	.value {
		color: #333333;
		flex: 1;
	}
	
	.active-text {
		color: #34C759;
	}
	
	.paused-text {
		color: #FF3B30;
	}
	
	.stats-row {
		display: flex;
		justify-content: space-around;
		margin-bottom: 30rpx;
	}
	
	.stats-item {
		text-align: center;
		flex: 1;
	}
	
	.stats-value {
		font-size: 40rpx;
		color: #007AFF;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.stats-label {
		font-size: 24rpx;
		color: #666666;
	}
	
	.chart-container {
		height: 400rpx;
		padding: 20rpx 0;
	}
	
	.score-distribution {
		display: flex;
		height: 100%;
		justify-content: space-around;
		align-items: flex-end;
	}
	
	.dist-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 18%;
	}
	
	.dist-bar {
		width: 100%;
		background-color: #007AFF;
		border-radius: 8rpx 8rpx 0 0;
		display: flex;
		justify-content: center;
		align-items: flex-start;
		padding-top: 10rpx;
		min-height: 30rpx;
	}
	
	.dist-count {
		color: #ffffff;
		font-size: 24rpx;
	}
	
	.dist-label {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #666666;
	}
	
	.question-error-rate {
		height: 100%;
		overflow-y: auto;
	}
	
	.error-item {
		margin-bottom: 20rpx;
	}
	
	.error-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8rpx;
	}
	
	.question-number {
		font-size: 24rpx;
		color: #333333;
	}
	
	.error-rate {
		font-size: 24rpx;
		color: #FF3B30;
	}
	
	.error-bar-container {
		width: 100%;
		height: 20rpx;
		background-color: #eeeeee;
		border-radius: 10rpx;
	}
	
	.error-bar {
		height: 100%;
		background-color: #FF3B30;
		border-radius: 10rpx;
	}
	
	.share-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}
	
	.share-content {
		width: 80%;
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 40rpx;
	}
	
	.share-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.share-info {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
	}
	
	.share-info text {
		margin-bottom: 15rpx;
		word-break: break-all;
	}
	
	.share-actions {
		display: flex;
		justify-content: space-around;
	}
	
	.share-btn {
		flex: 1;
		margin: 0 10rpx;
		background-color: #007AFF;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
	}
	
	.share-cancel {
		background-color: #999999;
	}
</style> 